package org.bjf.modules.user.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import lombok.Data;
import org.bjf.exception.ServiceException;
import org.bjf.modules.core.web.core.LoginInfo;
import org.bjf.modules.sys.enums.Permission;
import org.bjf.modules.user.bean.User;
import org.bjf.modules.user.enums.UserMsgCode;
import org.bjf.modules.user.enums.UserRedisKey;
import org.bjf.modules.user.query.UserQuery;
import org.bjf.modules.user.service.UserService;
import org.bjf.utils.IpUtil;
import org.bjf.utils.MD5Util;
import org.bjf.utils.RedisUtil;
import org.bjf.utils.TokenUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author bjf
 */
@RestController
@Validated
@RequestMapping("security")
@Permission(resSn = "security", resDesc = "安全管理权限")
public class SecurityController {

  @Resource
  private RedisUtil redis;

  @Resource
  private UserService userService;

  @RequestMapping("register")
  public void register(@RequestParam @NotBlank String username,
      @RequestParam @NotBlank String password) {
    //===1、看用户名是否已存在
    UserQuery query = new UserQuery();
    query.setUsername(username);
    int count = userService.count(query);
    if (count > 0) {
      throw new ServiceException(UserMsgCode.USER_HAS_EXIST);
    }

    //===2、新增用户
    User user = new User();
    user.setUsername(username);
    user.setPassword(MD5Util.encode(password));
    userService.add(user);
  }

  @RequestMapping("login")
  public LoginResp login(@RequestParam @NotBlank String username,
      @RequestParam @NotBlank String password, HttpServletRequest request) {
    //===1、验证用户名密码
    UserQuery query = new UserQuery();
    query.setUsername(username);
    User loginUser = userService.getOne(query);
    if (loginUser == null || !MD5Util.validDigest(password, loginUser.getPassword())) {
      throw new ServiceException(UserMsgCode.USER_WRONG);
    }
    //===2、登录成功，生成token并将登录用户信息写入redis
    Long userId = loginUser.getUserId();
    String ip = IpUtil.getClientIp(request);
    String accessToken = TokenUtil.genToken(userId, ip);
    String userKey = UserRedisKey.TOKEN_API.as(accessToken);
    LoginInfo loginInfo = LoginInfo
        .buildLoginInfo(accessToken, userId, loginUser.getUsername(), ip);
    // 15天过期
    long timeout = 86400 * 15L;
    redis.setex(userKey, loginInfo, timeout);

    //===3、返回登录信息-accessToken
    LoginResp loginResp = new LoginResp();
    loginResp.setAccessToken(accessToken);
    return loginResp;
  }

  @Data
  private static class LoginResp {

    private String accessToken;
  }
}
